package com.panshi.filter;

import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Order(1) //表示过滤器的顺序，假设我们有多个过滤器，你如何确定过滤器的执行顺序？这个注解就是规定过滤器的顺序。
@WebFilter(filterName = "piceaFilter", urlPatterns = "/*" , initParams = {
        @WebInitParam(name = "URL", value = "http://localhost:1011")})
public class MyFilter implements Filter {

    private String url;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("我是过滤器的执行方法，客户端向Servlet发送的请求被我拦截到了");

        System.out.println("当前用户ip");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        System.out.println(String.valueOf(request.getRemoteAddr()));
        String path = request.getServletPath();

        String auto="";
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("1b12ebc9bf976801fd564c64867366c5")) {
                    auto= cookie.getValue();
                }
            }
        }


        if("/consult/addComment".equals(path)){
            if(auto==null || auto==""){
                ((HttpServletResponse)servletResponse).sendRedirect("/login");
            }
        }



        filterChain.doFilter(servletRequest, servletResponse);
        System.out.println("我是过滤器的执行方法，Servlet向客户端发送的响应被我拦截到了");
    }

    @Override
    public void destroy() {

    }
}
